package com.jiai.live.im;

import com.jiai.core.util.SpringUtil;
import com.jiai.live.im.handler.ChatRoomAttr;
import com.jiai.live.im.handler.ChatRoomHandler;
import com.jiai.live.im.message.*;
import com.jiai.redis.util.RedisUtil;

import io.netty.channel.ChannelHandlerContext;
import io.netty.util.Attribute;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class LiveMessageThread implements Runnable{
	private static final Logger log= LoggerFactory.getLogger(LiveMessageThread.class);
	private Object msg;
	private ChannelHandlerContext ctx;
	public LiveMessageThread(ChannelHandlerContext ctx, Object msg){
		this.msg=msg;
		this.ctx=ctx;
	}
	@Override
	public void run() {



			if(msg instanceof LoginRoomMassage){
				LoginRoomMassage loginRoomMassage= (LoginRoomMassage) msg;
				Attribute<ChatRoomAttr> attr=ctx.attr(ChatRoomHandler.CHAT_ROOM_ATTR);
				ChatRoomAttr roomAttr=new ChatRoomAttr(loginRoomMassage.getUserId(), loginRoomMassage.getRoomId());
				attr.setIfAbsent(roomAttr);
				RoomManage.getInstance().add(loginRoomMassage.getRoomId(), loginRoomMassage.getUserId(), ctx);
				RoomManage.getInstance().broadcastRoom(loginRoomMassage.getRoomId(), loginRoomMassage, loginRoomMassage.getUserId());
				log.info("用户:{},进入了直播间:{}",loginRoomMassage.getUserId(),loginRoomMassage.getRoomId());
				return;
			}

			if(msg instanceof GiftMssage){
				GiftMssage giftMssage= (GiftMssage) msg;
				RoomManage.getInstance().broadcastRoom(giftMssage.getLiveId(), giftMssage, giftMssage.getUserId());
				log.info("用户:{},送给了主播:{},{}个{}礼物",giftMssage.getUserId(),giftMssage.getLiveId());
				log.info("{}个{}礼物",giftMssage.getNum(),giftMssage.getGiftName());
				return;
			}
			if(msg instanceof LiveMessage){
				LiveMessage liveMessage= (LiveMessage) msg;
				RoomManage.getInstance().broadcastRoom(liveMessage.getLiveId(), liveMessage, liveMessage.getForm());
				log.info("用户:{},在{}直播间,发送了一条消息",liveMessage.getNickName(),liveMessage.getLiveId());
				return;
			}
			if(msg instanceof BarrageMessage){
				BarrageMessage barrageMessage= (BarrageMessage) msg;
				RoomManage.getInstance().broadcastRoom(barrageMessage.getRoomId(), barrageMessage);
				log.info("用户:{},在{}直播间,发送了一条弹幕消息",barrageMessage.getNickName(),barrageMessage.getRoomId());

				return;
			}
			if(msg instanceof BroadcastMessage){
				BroadcastMessage msg=new BroadcastMessage();
				RoomManage.getInstance().broadcastALL(msg);
				log.info("用户:{},发送了一条全站广播消息",msg.getNickName());
				return;
			}
	}


	private RedisUtil getRedisUtil(){
		return SpringUtil.getBean(RedisUtil.class);
	}
}
